//从utils/auth.js中探需导入setToken、getToken、RemoveToken
import { getToken, setToken, removeToken } from "@/utils/auth";
import { login, getUserInfo } from "@/api/user";

const state = {
  token: getToken(), //调用getToken,从缓存中读取token初始值
  userInfo: {}, //存储登录用户资料状态
};

const mutations = {
  //设置token
  setToken(state, token) {
    state.token = token;
    //将token同步到缓存中
    setToken(token);
  },
  //清除token
  removeToken(state) {
    //清除vuex中的token
    (state.token = null),
      //清除缓存中的token
      removeToken();
  },
  setUserInfo(state, userInfo) {
    state.userInfo = userInfo;
  },
};
const actions = {
  //登录action
  async login(context, data) {
    //将登录信息拿去请求登录接口:调用api中的login接口
    //如果登录成功，接口会返回token
    const token = await login(data);
    context.commit("setToken", token);
  },
  //获取登录用户个人资料action
  async getUserInfo(context) {
    //调用api接口user.js中的getUserInfo方法获取到登录用户信息
    const result = await getUserInfo();
    //将获取到的用户信息保存到vuex中
    context.commit("setUserInfo", result);
  },
  //退出登录action
  async logout(context) {
    context.commit("removeToken"); //清除token
    context.commit("setUserInfo", {}); //清除登录用户信息
  },
};

export default {
  namespaced: true,
  state,
  mutations,
  actions,
};
